<template>
  <div class="app-container">
    <ProTable
      :columns.sync="columns"
      :showSearch.sync="showSearch"
      :getList="getList"
      :loading="loading"
      :resetQuery="resetQuery"
      :tableData="tableData"
    >
      <template #pagination>
        <pagination
          v-show="pageTotal > 0"
          :total="pageTotal"
          :page-sizes="[10, 20, 50, 100, 200, 300, 500]"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </template>
      <template #form>
        <el-form :model="queryParams" ref="queryForm" size="small">
          <el-row>
            <el-form-item prop="skuNo">
              <el-input :placeholder="$t('sku')" v-model="queryParams.skuNo" @keyup.enter.native="getList" />
            </el-form-item>
            <el-form-item prop="spNo">
              <el-input :placeholder="$t('库位号')" v-model="queryParams.spNo" @keyup.enter.native="getList" />
            </el-form-item>

            <el-form-item prop="skuExtra">
              <el-input :placeholder="$t('额外sku')" v-model="queryParams.skuExtra" />
            </el-form-item>
            <el-form-item prop="transportAll">
              <el-select :placeholder="$t('是否出运')" v-model="queryParams.transportAll">
                <el-option :label="$t('是')" value="1"></el-option>
                <el-option :label="$t('否')" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="ser">
              <el-input :placeholder="$t('二维码查询')" v-model="queryParams.ser" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item prop="purchaseTime">
              <el-date-picker
                :placeholder="$t('采购日期范围')"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                :start-placeholder="$t('开始时间')"
                :end-placeholder="$t('结束时间')"
                v-model="queryParams.purchaseTime"
                type="datetimerange"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item prop="hitShelfAll">
              <el-select :placeholder="$t('是否全部上架')" v-model="queryParams.hitShelfAll">
                <el-option :label="$t('是')" value="1"></el-option>
                <el-option :label="$t('否')" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="receiveGoodsNum">
              <el-select :placeholder="$t('是否收货')" v-model="queryParams.receiveGoodsNum">
                <el-option :label="$t('是')" value="1"></el-option>
                <el-option :label="$t('否')" value="0"></el-option>
              </el-select>
            </el-form-item>
            <!-- 审核状态 -->
            <el-form-item>
              <el-select :placeholder="$t('审核状态')" v-model="queryParams.status">
                <!-- 0-未审核 1-审核 -->
                <el-option :label="$t('未审核')" value="0"></el-option>
                <el-option :label="$t('已审核')" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-select :placeholder="$t('采购类型')" v-model="queryParams.type">
                <!-- 0-未审核 1-审核 -->
                <el-option :label="$t('国内采购')" value="1"></el-option>
                <el-option :label="$t('酒水采购')" value="2"></el-option>
                <el-option :label="$t('日本当地采购')" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item prop="janCode">
              <el-input
                v-model="queryParams.janCode"
                :placeholder="$t('jan编码')"
                clearable
                @keyup.enter.native="getList"
              />
            </el-form-item>
          </el-row>
        </el-form>
      </template>
      <template #actions>
        <el-tooltip
          effect="dark"
          :content="$t('出运后未入库的产品报废')"
          v-hasPermi="['distribution:purchase:scrapSku']"
          placement="top-start"
        >
          <el-button @click="handleTransportScrap" icon="el-icon-warning-outline" plain size="mini" type="primary">
            {{ $t('运输报废') }}
          </el-button>
        </el-tooltip>
        <el-tooltip
          v-hasPermi="['distribution:purchase:scrapSkuWarehouse']"
          effect="dark"
          :content="$t('入库后的产品报废')"
          placement="top-start"
        >
          <el-button @click="handleWarehouseScrap" icon="el-icon-warning-outline" plain size="mini" type="success">
            {{ $t('仓库报废') }}
          </el-button>
        </el-tooltip>
      </template>
      <template #skuNo="{ row }">
        <div @click="handleEdits(row)" style="cursor: pointer; color: #1890ff">
          {{ row.skuNo }}
        </div>
      </template>
      <template #imgUrl="{ row }">
        <el-image
          fit="contain"
          style="width: 50px; height: 50px"
          :key="Math.random()"
          v-hover="row.imgUrl"
          :src="row.imgUrl + '?x-oss-process=image/resize,w_100/quality,q_70'"
        />
      </template>
      <template #deliverWayCn="{ row }">
        <span>{{ handleDeliveGood(row.deliverWayCn) }}</span>
      </template>
      <template #type="{ row }">
        <!-- 采购类型 1-国内采购 2-酒水采购 3-日本当地采购 -->
        <div :style="{ color: $randomColor(row.type) }" v-if="row.type == 1">
          {{ $t('国内采购') }}
        </div>
        <div :style="{ color: $randomColor(row.type) }" v-if="row.type == 2">
          {{ $t('酒水采购') }}
        </div>
        <div :style="{ color: $randomColor(row.type) }" v-if="row.type == 3">
          {{ $t('日本当地采购') }}
        </div>
      </template>
      <template #status="{ row }">
        <!-- 审核状态 0-未审核 1-审核 -->
        <div v-if="row.status == 0" style="color: red">
          {{ $t('未审核') }}
        </div>
        <div v-if="row.status == 1" style="color: green">
          {{ $t('已审核') }}
        </div>
      </template>
      <template #receiveGoodsNum="{ row }">
        <div style="color: #13ce66; cursor: pointer" @click="handleReceiveGoods(row)" v-if="row.receiveGoodsNum">
          {{ row.receiveGoodsNum }}
        </div>
        <div style="color: #409eff; cursor: pointer" v-else @click="handleReceiveGoods(row)">未收货</div>
      </template>
      <template #isSerializable="{ row }">
        <el-link :underline="false" v-if="row.isSerializable" @click="handleDiliverDetail(row)" type="success">
          {{ row.serializableNum }}
        </el-link>
        <el-popconfirm @confirm="handleDiliver(row.id)" v-else :title="$t('确认分配?')">
          <div slot="reference">
            <el-button type="text" size="small">
              {{ $t('分配') }}
            </el-button>
            <el-button
              v-hasPermi="['distribution:purchase:serImport']"
              @click.stop="handleImport(row)"
              type="text"
              size="small"
            >
              {{ $t('导入') }}
            </el-button>
          </div>
        </el-popconfirm>
      </template>
      <template #encasementNum="{ row }">
        <div
          style="color: #409eff; cursor: pointer"
          v-hasPermi="['distribution:batch:getBatchSerByPurchase']"
          @click="handleEncasementNum(row)"
        >
          {{ row.encasementNum || 0 }}
        </div>
      </template>
      <template #transportNum="{ row }">
        <div>{{ row.transportNum || 0 }}</div>
      </template>
      <template #hitShelfNum="{ row }">
        <div style="color: #409eff; cursor: pointer" @click="isShowBatchScanCodeShelves(row)">
          {{ row.hitShelfNum }}
        </div>
      </template>
      <template #option="{ row }">
        <el-dropdown @command="(command) => handleCommand(command, row)">
          <span class="el-dropdown-link">
            {{ $t('更多') }}
            <i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-hasPermi="['distribution:purchase:info']" command="handleDetail">
              {{ $t('详情') }}
            </el-dropdown-item>
            <el-dropdown-item v-hasPermi="['distribution:purchase:remove']" command="handleDelete">
              {{ $t('删除') }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
    </ProTable>
    <!-- 收货 -->
    <el-dialog
      :visible.sync="receiveGoodsInfo.show"
      :title="receiveGoodsInfo.form.skuNo"
      width="700px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div>
        <el-form
          ref="receiveGoodsForm"
          :model="receiveGoodsInfo.form"
          :rules="receiveGoodsInfo.rules"
          size="small"
          label-width="80px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('采购数量')" prop="type">
                <el-input disabled v-model="receiveGoodsInfo.form.num" type="number" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('退款数量')">
                <el-input disabled v-model="receiveGoodsInfo.form.refundNum" type="number" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('收货数量')" prop="receiveGoodsNum">
                <!-- <el-input v-model="receiveGoodsInfo.form.receiveGoodsNum" type="number" /> -->
                <el-input-number
                  style="width: 100%"
                  v-model="receiveGoodsInfo.form.receiveGoodsNum"
                  controls-position="right"
                  :min="0"
                  :max="receiveGoodsInfo.form.num - receiveGoodsInfo.form.refundNum"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="receiveGoodsInfo.show = false">
          {{ $t('取消') }}
        </el-button>
        <el-button type="primary" @click="confirmReceiveGoods">
          {{ $t('确定') }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 装箱数量 -->
    <el-dialog
      :visible.sync="encasementNumInfo.show"
      :title="$t('装箱数量')"
      width="700px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div>
        <el-form
          ref="encasementNumForm"
          :model="encasementNumInfo.form"
          :rules="encasementNumInfo.rules"
          size="small"
          label-width="80px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('箱子号')" prop="batchBoxId">
                <el-select style="width: 100%" v-model="encasementNumInfo.form.batchBoxId">
                  <el-option
                    :label="item.boxNo"
                    :value="item.id"
                    v-for="(item, index) in encasementNumInfo.encasementList"
                    :key="index"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('装箱数量')" prop="num">
                <el-input v-model="encasementNumInfo.form.num" type="num" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="encasementNumInfo.show = false">
          {{ $t('取消') }}
        </el-button>
        <el-button type="primary" @click="confirmEncasementNum">
          {{ $t('确定') }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 创建批次 -->
    <el-dialog
      :visible.sync="showAddBtch"
      :title="$t('创建批次')"
      width="500px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddBtch = false">
          {{ $t('取消') }}
        </el-button>
        <el-button type="primary" @click="showAddBtch = false">
          {{ $t('确定') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 追加箱子 -->
    <el-dialog
      :visible.sync="appendBox"
      :title="$t('追加箱子')"
      width="500px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="appendBox = false">
          {{ $t('取消') }}
        </el-button>
        <el-button type="primary" @click="appendBox = false">
          {{ $t('确定') }}
        </el-button>
      </div>
    </el-dialog>

    <QR
      :title="$t('详情')"
      width="74"
      height="74"
      :dialogVisible="diliverInfo.show"
      :barcodeNum="diliverInfo.qrData"
      @handleClose="diliverInfo.show = false"
    />

    <!-- 详情 -->
    <el-dialog
      v-if="detailInfo.show"
      :visible.sync="detailInfo.show"
      :title="$t('详情')"
      width="800px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <el-form label-width="120px" ref="saveForm" :model="detailInfo.form" :rules="detailInfo.rules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="sku">
              <el-input disabled v-model="detailInfo.form.skuNo" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 库位号 -->
            <el-form-item :label="$t('库位号')">
              <el-input disabled v-model="detailInfo.form.spNo" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 图片 -->
            <el-form-item :label="$t('图片')">
              <el-image
                style="width: 60px; height: 60px; object-fit: cover"
                lazy
                class="goods-img-mini"
                :src="detailInfo.form.imgUrl + '?x-oss-process=image/resize,w_100/quality,q_70'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 采购数量 -->
            <!-- :disabled="detailInfo.form.status == 1" -->
            <el-form-item :label="$t('采购数量')" prop="num">
              <el-input-number
                disabled
                @change="setDetailInfoNum"
                style="width: 100%"
                v-model="detailInfo.form.num"
                controls-position="right"
                :precision="0"
                :min="1"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 品名 -->
            <el-form-item :label="$t('品名')">
              <el-input disabled v-model="detailInfo.form.spNo" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 国内发货方式 -->
            <el-form-item :label="$t('国内发货方式')">
              <el-select disabled style="width: 100%" v-model="detailInfo.form.deliverWayCn">
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="(item, index) in deliver_goods_cn_list"
                  :key="index"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 在库数量 -->
            <el-form-item :label="$t('在库数量')">
              <el-input disabled v-model="detailInfo.form.totalStock" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 云数量 -->
            <el-form-item l :label="$t('云数量')">
              <el-input disabled v-model="detailInfo.form.cloudStock" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <!-- 采购日期 -->
          <el-col :span="12">
            <el-form-item :label="$t('采购日期')">
              <el-input disabled v-model="detailInfo.form.createTime" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 采购类型 -->
            <el-form-item :label="$t('采购类型')">
              <el-select disabled style="width: 100%" v-model="detailInfo.form.type">
                <el-option
                  :label="item.label"
                  :value="+item.value"
                  v-for="(item, index) in purchase_type_list"
                  :key="index"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('付款总额')" prop="payPrice">
              <el-input
                :disabled="detailInfo.form.status == 1"
                type="number"
                @change="setDetailInfo"
                style="width: 100%"
                :placeholder="$t('请输入')"
                v-model="detailInfo.form.payPrice"
              >
                <!~~ 付款总价单位 1-RMB 2-JPY 3-USD ~~>
                <el-button slot="append">
                  <el-select disabled style="width: 100px" v-model="detailInfo.form.payPriceUnit">
                    <el-option label="RMB" :value="1" />
                    <el-option label="JPY" :value="2" />
                    <el-option label="USD" :value="3" />
                  </el-select>
                </el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!~~ 总货值 ~~>
            <el-form-item :label="$t('总货值')">
              <el-input disabled v-model="detailInfo.form.skuTotalValue">
                <template slot="suffix">JPY</template></el-input
              >
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row :gutter="20">
          <!-- <el-col :span="12">
            <el-form-item :label="$t('单价')">
              <el-input disabled v-model="detailInfo.form.skuUnitPrice">
                <template slot="suffix">JPY</template></el-input
              >
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <!-- 收货数量 -->
            <el-form-item :label="$t('收货数量')">
              <el-input disabled v-model="detailInfo.form.receiveGoodsNum" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 退款数量 -->
            <el-form-item :label="$t('退款数量')">
              <el-input disabled v-model="detailInfo.form.refundNum" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 退款金额 -->
            <el-form-item :label="$t('退款金额')">
              <el-input disabled v-model="detailInfo.form.refundAmount">
                <!-- 	退款金额单位 1-RMB 2-JYP 3-USD -->
                <template slot="suffix">
                  <div v-if="detailInfo.form.refundAmountUnit == 1">RMB</div>
                  <div v-if="detailInfo.form.refundAmountUnit == 2">JYP</div>
                  <div v-if="detailInfo.form.refundAmountUnit == 3">USD</div>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 装箱数量 -->
            <el-form-item :label="$t('装箱数量')">
              <el-input disabled v-model="detailInfo.form.encasementNum" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 出运数量 -->
            <el-form-item :label="$t('出运数量')">
              <el-input disabled v-model="detailInfo.form.transportNum" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 上架数量 -->
            <el-form-item :label="$t('上架数量')">
              <el-input disabled v-model="detailInfo.form.hitShelfNum" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 是否分配序列号 -->
            <el-form-item :label="$t('是否分配序列号')">
              <div style="color: #13ce66" v-if="detailInfo.form.isSerializable">
                <!-- 已分配 -->
                {{ $t('是') }}
              </div>
              <div style="color: orange" v-else>
                <!-- 未分配 -->
                {{ $t('否') }}
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('采购备注')">
              <el-input disabled type="textarea" :rows="4" v-model="detailInfo.form.purchaseRemark" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <!-- 汇率 -->
            <el-form-item :label="$t('汇率')">
              {{ detailInfo.form.exchangeRate }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('采购单备注')">
              <el-input type="textarea" :rows="4" v-model="detailInfo.form.remark" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailInfo.show = false">
          <!-- 关闭 -->
          {{ $t('关闭') }}
        </el-button>
        <!--
            审核状态
            0-未审核
            1-审核
            -->
        <!-- 审核前可以修改，审核后不能修改 -->
        <el-button @click="handleSave" type="primary" v-if="detailInfo.form.status == 0">
          <!-- 保 存 -->
          {{ $t('保存') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 扫码上架 -->
    <el-dialog
      class="myDialog"
      :before-close="clearBatchScanCodeShelves"
      :visible.sync="BatchScanCodeShelves"
      :title="$t('扫码上架')"
      width="800px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <h3 class="batchTitle">SKU:{{ BatchScanCodeShelvesForm.data.skuNo }}</h3>
      <div class="checkType">
        <el-radio-group v-model="ShelvesType">
          <el-radio :label="1" style="margin-right: 200px">{{ $t('扫码上架') }}</el-radio>
          <el-radio :label="2">{{ $t('批量上架') }}</el-radio>
        </el-radio-group>
      </div>
      <!-- 扫码上架 -->
      <div v-if="ShelvesType == 1" class="scanStatus">
        <div class="checkTypesContent">
          <div :class="scanCodeType == 1 ? 'checkTypes activecheckTypes' : 'checkTypes'" @click="codeScanner(1)">
            {{ $t('扫码上架') }}
          </div>
          <div :class="scanCodeType == 2 ? 'checkTypes activecheckTypes' : 'checkTypes'" @click="codeScanner(2)">
            {{ $t('查看序列号上架情况') }}
          </div>
        </div>

        <div class="contentList" v-if="scanCodeType == 1">
          <div class="fatherContent">
            <div class="seriesNum">{{ $t('系列号') }}</div>
            <div class="ShelfStatus">{{ $t('上架情况') }}</div>
          </div>
          <!-- 输入 -->
          <div class="fatherContent">
            <div class="seriesNum">
              <el-input v-model="scanCodeForm.scan" @change="changeData"></el-input>
            </div>
            <div class="ShelfStatus"></div>
          </div>
          <div class="fatherContent" v-for="(item, index) in BatchScanCodeShelvesList" :key="index">
            <div class="seriesNum">
              {{ item.series }}
            </div>
            <div class="ShelfStatus">
              <span v-if="item.status == 5" style="color: rgb(175, 136, 6)"> {{ $t('序列号已过期') }} </span>
              <span v-if="item.status == 5" style="color: rgb(175, 136, 6)"> {{ $t('采购单未收货') }} </span>
              <span v-if="item.status == 4" style="color: rgb(175, 136, 6)"> {{ $t('系统异常') }} </span>
              <span v-if="item.status == 3" style="color: rgb(175, 136, 6)"> {{ $t('序列号不存在') }} </span>
              <span v-if="item.status == 2" style="color: red"> {{ $t('重复上架') }} </span>
              <span v-if="item.status == 1" style="color: #13ce66"> {{ $t('上架成功') }} </span>
            </div>
          </div>
        </div>
        <div class="contentList" v-if="scanCodeType == 2">
          <div class="fatherContent">
            <div class="seriesNum">{{ $t('系列号') }}</div>
            <div class="ShelfStatus">{{ $t('上架情况') }}</div>
          </div>
          <div class="fatherContent" v-for="(item, index) in LookBatchScanCodeShelvesList" :key="index">
            <div class="seriesNum">
              {{ item.id }}
            </div>
            <div class="ShelfStatus">
              <span v-if="item.isOnShelf == 0" style="color: red"> {{ $t('未上架') }} </span>
              <span v-if="item.isOnShelf == 1" style="color: #13ce66"> {{ $t('已上架') }} </span>
            </div>
          </div>
        </div>
      </div>
      <!-- 批量上架 -->
      <div v-else class="beatchAllFather">
        <div class="beatchAll">
          {{ $t('批量上架会一次性全部上架所有已分配序列号的产品,没有全部到货不要使用使用后不能再扫码上架') }}
        </div>
        <div slot="footer" class="beatchAllFooter">
          <el-button @click="clearBatchScanCodeShelves('cancel')">{{ $t('取消') }}</el-button>
          <el-button type="primary" @click="AllSubmit">{{ $t('确认') }}</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- sku详情/修改 -->
    <Skucontmoduler @relaod="relaod" ref="Skucontmoduler"></Skucontmoduler>
    <!-- 分配列表 -->
    <el-dialog
      class="myDialog"
      :before-close="allocationFlageClose"
      :visible.sync="allocationFlage"
      :title="$t('分配列表')"
      width="800px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div class="scanStatus">
        <el-row style="margin-bottom: 20px">
          <el-col :offset="1" :span="7">
            <div class="goods-img-box">
              <el-image
                fit="contain"
                style="width: 60px; height: 60px; object-fit: cover"
                lazy
                class="goods-img-mini"
                :src="QuantityReceived.imgUrl + '?x-oss-process=image/resize,w_100/quality,q_70'"
              />
            </div>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-row style="margin-bottom: 20px"> {{ $t('sku编号') }}:{{ QuantityReceived.skuNo }}</el-row>
            <el-row style="margin-bottom: 20px"> {{ $t('库位号') }}:{{ QuantityReceived.spNo }}</el-row>
            <el-row> {{ $t('是否会过期') }}:{{ QuantityReceived.isExpired == 1 ? '是' : '否' }}</el-row>
          </el-col>
          <el-col :offset="1" :span="7">
            <el-row style="margin-bottom: 20px"> {{ $t('已收货数量') }}:{{ QuantityReceived.receiveGoodsNum }}</el-row>
            <el-row> {{ $t('序列号数量') }}:{{ diliverInfo.data.length }}</el-row>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-button
            :disabled="diliverInfo.tableCheck.length == 0"
            type="primary"
            plain
            size="mini"
            @click="printQrCode"
          >
            {{ $t('打印二维码') }}
          </el-button>
          <el-popconfirm style="margin: 0 5px" @confirm="distributionSerialNumContinue" :title="$t('是否继续分配?')">
            <el-button type="success" slot="reference" plain size="mini">
              {{ $t('继续分配') }}
            </el-button>
          </el-popconfirm>
          <el-radio-group v-model="isPage" @change="resetSelectData">
            <el-radio label="1">{{ $t('不分页') }}</el-radio>
            <el-radio label="2">{{ $t('分页') }}</el-radio>
          </el-radio-group>

          <el-button
            type="text"
            v-hasPermi="['distribution:purchase:setIsExpiredTime']"
            style="float: right"
            @click="subExpirationTime(1, null)"
            >设置全部过期时间</el-button
          >
          <el-button type="text" style="float: right; margin-right: 10px" @click="printSeatNumber"> 打印箱号</el-button>
        </el-row>
        <!-- 不分页列表 -->
        <!-- { name: $t('过期时间'), prop: 'id', style: { flex: 1.5 } }, -->
        <v-list
          class="VList"
          v-if="isPage == 1"
          @rowSelect="(rows) => (diliverInfo.tableCheck = rows)"
          :list-data="diliverInfo.data"
          :prop="[
            { name: $t('序号'), prop: 'indexNo', style: { flex: 0.6 } },
            { name: $t('序列号'), prop: 'id', style: { flex: 1.5 } },

            { name: $t('过期时间'), prop: 'expiredTime' },
            { name: $t('装箱情况'), prop: 'isBox' },
            { name: $t('出库情况'), prop: 'isOutWarehouse' },
            { name: $t('上架情况'), prop: 'isOnShelf' },
            {
              name: $t('操作'),
              style: { flex: 1.5 },
              prop: [
                {
                  name: $t('删除'),
                  style: 'color:red;',
                  permission: ['distribution:purchase:deletePurchaseSkuSerializable'],
                  click: (row) => deleteDistr(row),
                  disabled: (row) => row.isOnShelf == 1,
                },
                {
                  name: $t('过期时间'),
                  permission: ['distribution:purchase:setIsExpiredTime'],
                  click: (row) => {
                    subExpirationTime(0, row)
                  },
                  disabled: (row) => false,
                },
              ],
            },
          ]"
          :view-count="20"
        >
        </v-list>
        <!-- 分页列表 -->
        <div v-if="isPage == 2" class="PagingList">
          <el-table
            height="526"
            @selection-change="(rows) => (diliverInfo.tableCheck = rows)"
            ref="TableRef"
            :data="diliverInfo.pageData"
          >
            <el-table-column align="center" type="selection" width="48" />
            <!-- 序号 -->
            <el-table-column :label="$t('序号')" align="center" width="50" show-overflow-tooltip prop="serial" />
            <!-- 序列号 -->
            <el-table-column align="center" prop="id" width="170" :label="$t('序列号')" />
            <!-- 过期时间 -->
            <el-table-column align="center" prop="expiredTime" width="100" :label="$t('过期时间')">
              <template slot-scope="{ row }">
                {{ row.expiredTime ? row.expiredTime : '-' }}
              </template>
            </el-table-column>

            <!-- 装箱情况 -->
            <el-table-column align="center" show-overflow-tooltip prop="isBox" label="装箱情况">
              <!-- // 是否装箱 0-否 1-是 -->
              <template slot-scope="{ row }">
                <div v-if="row.isBox == 1" style="color: green">
                  {{ $t('是') }}
                </div>
                <div v-if="row.isBox == 0" style="color: red">
                  {{ $t('否') }}
                </div>
              </template>
            </el-table-column>
            <!-- 出库情况 -->
            <el-table-column align="center" show-overflow-tooltip prop="isOutWarehouse" label="出库情况">
              <!-- // isOutWarehouse 0-未出库 1-已出库 -->
              <template slot-scope="{ row }">
                <div v-if="row.isOutWarehouse == 1" style="color: green">{{ $t('已出库') }}</div>
                <div v-if="row.isOutWarehouse == 0" style="color: red">{{ $t('未出库') }}</div>
              </template>
            </el-table-column>
            <!-- 上架情况 -->
            <el-table-column align="center" show-overflow-tooltip prop="isOnShelf" label="上架情况">
              <!-- // 上架情况 0-否 1-是 -->
              <template slot-scope="{ row }">
                <div v-if="row.isOnShelf == 1" style="color: green">{{ $t('已上架') }}</div>
                <div v-if="row.isOnShelf == 0" style="color: red">{{ $t('未上架') }}</div>
              </template>
            </el-table-column>

            <el-table-column align="center" fixed="right" width="110" :label="$t('操作')">
              <template slot-scope="{ row }">
                <div style="display: flex; justify-content: space-between; width: 100%">
                  <el-button
                    type="text"
                    v-hasPermi="['distribution:purchase:deletePurchaseSkuSerializable']"
                    @click="deleteDistr(row)"
                    :disabled="row.isOnShelf == 1"
                  >
                    <span style="color: red">
                      {{ $t('删除') }}
                    </span>
                  </el-button>
                  <el-button
                    type="text"
                    v-hasPermi="['distribution:purchase:setIsExpiredTime']"
                    @click="subExpirationTime(0, row)"
                  >
                    {{ $t('过期时间') }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="diliverInfo.pageTotal > 0"
            :total="diliverInfo.pageTotal"
            :page-sizes="[20, 30, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]"
            :page.sync="diliverInfo.queryParams.pageNum"
            :limit.sync="diliverInfo.queryParams.pageSize"
            @pagination="getPageDiliverList"
          />
        </div>
      </div>
    </el-dialog>
    <!-- 设置时间 -->
    <el-dialog
      :before-close="cancelExpirationTime"
      :visible.sync="ExpirationTime"
      :title="$t('设置序列号过期时间')"
      width="300px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <div style="width: 100%; text-align: center">
        <el-date-picker
          v-model="QuantityReceived.ExpirationTimevalue"
          value-format="yyyy-M-dd"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
      </div>
      <div slot="footer">
        <el-button @click="cancelExpirationTime">{{ $t('取消') }}</el-button>
        <el-button type="primary" @click="setExpirationTime">{{ $t('确认') }}</el-button>
      </div>
    </el-dialog>
    <!-- 运输报废 -->
    <TransportScrap :show.sync="transportScrap.show" @getList="getList" :formData="transportScrap.formData" />
    <!-- 仓库报废 -->
    <WarehouseScrap :show.sync="warehouseScrap.show" @getList="getList" :formData="warehouseScrap.formData" />
    <!-- 导入 -->
    <Import
      :showTip="false"
      action="/distribution/purchase/serImport"
      templateUrl="distribution/purchase/serTempDownload"
      @success="getList"
      :query="importInfo.query"
      :fileName="importInfo.fileName"
      :show.sync="importInfo.show"
    >
    </Import>
    <SeatNumber
      title="详情"
      :dialogVisible.sync="SeatNumberFormDataFlage"
      :FormData="QuantityReceived"
      @SeatNumberClose="SeatNumberClose"
    />
    <EncasementNum :show.sync="encasementNum.show" :formData="encasementNum.formData" />
  </div>
</template>

<script>
import {
  getConversionRateList,
  getPurchaseInfo,
  getSkuList,
  updatePurchase,
} from '@/api/purchasingManage/manufacturerPurchaseOrder'
import { listManufacturers } from '@/api/purchasingManage/manufacturers'
import EncasementNum from './components/encasementNum.vue'

import {
  batchEncasement,
  confirmReceiveGoods,
  deletePurchase,
  deletePurchaseSkuSerializable,
  distributionSerialNum,
  distributionSerialNumContinue,
  getBatchBoxList,
  getBatchNoPage,
  getPurchaseList,
  getSkuSerializableListBySkuIdPurchaseId,
  getSkuSerializableListBySkuIdPurchaseIdByPage,
  purchaseSkuSerializableBatch,
  purchaseSkuSerializableScanCode,
  setIsExpiredTime,
} from '@/api/purchasingManage/warehousePurchaseOrder'
import { distributorList } from '@/api/system/user'
import Import from '@/components/Import/index.vue'
import QR from '@/components/QrCode/newcode.vue'
import Skucontmoduler from '@/components/Skucontmoduler'
import VList from '@/components/v-list/index.vue'
import { useDict } from '@/utils/useDict'
import { Loading } from 'element-ui'
import SeatNumber from './components/SeatNumber.vue'
import TransportScrap from './components/transportScrap.vue'
import WarehouseScrap from './components/warehouseScrap.vue'
export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  name: 'WarehousePurchaseOrder',
  components: { QR, SeatNumber, Import, Skucontmoduler, VList, TransportScrap, WarehouseScrap, EncasementNum },
  data() {
    return {
      /**@type {ProTableColumns}*/
      columns: [
        {
          label: this.$t('sku编号'),
          prop: 'skuNo',
          width: 110,
          fixed: 'left',
          useSlot: true,
        },
        { label: this.$t('库位号'), prop: 'spNo', width: 110, fixed: 'left' },
        { label: this.$t('额外sku'), prop: 'skuExtra', width: 110, fixed: 'left' },
        { label: this.$t('采购数量'), prop: 'num', width: 110, fixed: 'left' },
        { label: this.$t('图片'), prop: 'imgUrl', width: 110, useSlot: true, fixed: 'left' },
        { label: this.$t('jan编码'), prop: 'janCode', width: 110 },
        { label: this.$t('品名'), prop: 'skuNameCn', width: 110 },
        { label: this.$t('国内发货方式'), prop: 'deliverWayCn', width: 110, useSlot: true },
        { label: this.$t('在库数量'), prop: 'totalStock', width: 110 },
        { label: this.$t('采购日期'), prop: 'createTime', width: 110 },
        { label: this.$t('供应商'), prop: 'distrName', width: 110 },
        { label: this.$t('采购类型'), prop: 'type', width: 110, useSlot: true },
        { label: this.$t('审核状态'), prop: 'status', width: 110, useSlot: true },
        { label: this.$t('退款数量'), prop: 'refundNum', width: 110 },
        { label: this.$t('收货数量'), prop: 'receiveGoodsNum', width: 110, useSlot: true },
        { label: this.$t('是否分配序列号'), prop: 'isSerializable', width: 110, useSlot: true },
        { label: this.$t('装箱数量'), prop: 'encasementNum', width: 110, useSlot: true },
        { label: this.$t('出运数量'), prop: 'transportNum', width: 110, useSlot: true },
        { label: this.$t('上架数量'), prop: 'hitShelfNum', width: 110, useSlot: true },
        { label: this.$t('采购备注'), prop: 'purchaseRemark', width: 110 },
        { label: this.$t('采购单备注'), prop: 'remark', width: 110 },
        { label: this.$t('操作'), prop: 'option', width: 110, fixed: 'right', useSlot: true },
      ],
      encasementNum: {
        show: false,
        formData: {},
      },
      SeatNumberFormDataFlage: false,
      /**关于打印库位号信息的数据 */
      SeatNumberFormData: {
        show: false,
      },
      /**
       * 导入组件的显示与隐藏
       */
      importInfo: {
        fileName: '',
        show: false,
        query: {},
      },
      /**设置过期时间 */
      ExpirationTime: false,
      /**运输报废 */
      transportScrap: {
        show: false,
        formData: {},
      },
      /**仓库报废 */
      warehouseScrap: {
        show: false,
        formData: {},
      },
      showSearch: false,
      loadingInstance: '',
      /**是否分页
       * @type {string|number}
       */
      isPage: '1',
      // 用户选择下拉列表
      selectUserTypeList: [],
      // 收货数量
      QuantityReceived: {
        receiveGoodsNum: 0,
        ExpirationTimevalue: '',
      },
      purchase_type_list: [],
      allocationFlage: false,
      scanCodeForm: { scan: '' },
      /**@type {string|number} */
      scanCodeType: '1',
      /**上架类型*/
      ShelvesType: 1,
      BatchScanCodeShelvesForm: {
        data: {},
        list: [],
      },
      LookBatchScanCodeShelvesList: [],
      BatchScanCodeShelvesList: [],
      BatchScanCodeShelves: false,
      /**汇率 */
      exchangeRateList: [],
      /**发货方式 */
      deliver_goods_cn_list: [],
      /**批次号 */
      batchNo: '',
      showName: '',
      form: {
        type: 1,
        payPriceUnit: 1,
        choice: 1,
        skuId: '',
      },
      /**新建批次 */
      showAddBtch: false,
      /**追加箱子 */
      appendBox: false,
      addForm: {},
      tableData: [],
      /**获取供应厂商列表  （厂家） */
      manufacturersList: [],
      skuList: [],
      showDialog: false,
      rules: {
        type: [{ required: true, message: '请输入', trigger: 'blur' }],
        skuId: [{ required: true, message: '请选择', trigger: 'blur' }],
        num: [{ required: true, message: '请输入', trigger: 'blur' }],
        payPrice: [{ required: true, message: '请输入', trigger: 'blur' }],
        skuTotalValue: [{ required: true, message: '请输入', trigger: 'blur' }],
        skuUnitPrice: [{ required: true, message: '请输入', trigger: 'blur' }],
        manufacturersId: [{ required: true, message: '请选择', trigger: 'blur' }],
      },
      addRules: {
        id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
        manufacturersName: [{ required: true, message: '厂家名称不能为空', trigger: 'blur' }],
        manufacturersTel: [{ required: true, message: '厂家电话不能为空', trigger: 'blur' }],
        principalName: [{ required: true, message: '负责人名称不能为空', trigger: 'blur' }],
        principalTel: [{ required: true, message: '负责人电话不能为空', trigger: 'blur' }],
        manufacturersAddress: [{ required: true, message: '厂家地址不能为空', trigger: 'blur' }],
        purchasePlatformLink: [{ required: true, message: '不能为空', trigger: 'blur' }],
        deliverPositionCn: [{ required: true, message: '中国发货仓库不能为空', trigger: 'blur' }],
        deliverWayCn: [{ required: true, message: '中国发货方式不能为空', trigger: 'blur' }],
        isDefault: [
          {
            required: true,
            message: '是否默认供应厂家不能为空',
            trigger: 'blur',
          },
        ],
        skuPackDemand: [{ required: true, message: '产品捆绑要求不能为空', trigger: 'blur' }],
        remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
      },
      /**数据总条数 */
      pageTotal: 0,
      loading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        purchaseTime: [],
      },
      /**收货 */
      receiveGoodsInfo: {
        show: false,
        title: '',
        form: {},
        rules: {
          receiveGoodsNum: [{ required: true, message: '请输入', trigger: 'blur' }],
          refundNum: [{ required: true, message: '请输入', trigger: 'blur' }],
          refundAmount: [{ required: true, message: '请输入', trigger: 'blur' }],
        },
      },
      /**装箱数量 */
      encasementNumInfo: {
        show: false,
        /**箱子号列表 */
        encasementList: [],
        title: '',
        form: {},
        rules: {
          batchBoxId: [{ required: true, message: '请输入', trigger: 'blur' }],
          num: [{ required: true, message: '请输入', trigger: 'blur' }],
        },
      },

      /**批次列表 */
      batchList: [],
      diliverInfo: {
        qrData: [],
        tableCheck: [],
        show: false,
        data: [],
        /**分页数据 */
        pageData: [],
        pageTotal: 0,

        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 20,
          purchaseId: '',
          skuId: '',
          ser: ',',
        },
      },
      /**详情 */
      detailInfo: {
        show: false,
        form: {},
      },
    }
  },
  created() {
    this.getList()
    this.get_deliver_goods_cn_list()
    // this.getManufacturers();
    getBatchNoPage().then((res) => {
      this.batchList = res.data
    })
    this.getDistributorList()
  },
  methods: {
    handleCommand(command, row) {
      this[command](row)
    },
    SeatNumberClose(val) {
      this.SeatNumberFormDataFlage = val
    },
    /**当前年月日 */
    getCurrentDate(format) {
      const currentDate = new Date() // 创建一个Date对象来表示当前日期和时间
      const year = currentDate.getFullYear() // 获取当前年份
      const month = currentDate.getMonth() + 1 // 获取当前月份（注意：月份从0开始，所以要加1）
      const day = currentDate.getDate() // 获取当前日期（天）

      // 如果你需要获取其他时间信息，比如小时、分钟、秒，也可以继续使用Date对象的方法

      // 返回一个包含年、月、日的字符串
      return `${year}${format}${month}${format}${day}`
    },
    printSeatNumber() {
      if (this.isPage == 1) {
        this.QuantityReceived.expiredTime = this.diliverInfo.data[0].expiredTime
      } else if (this.isPage == 2) {
        this.QuantityReceived.expiredTime = this.diliverInfo.pageData[0].expiredTime
      }
      this.QuantityReceived.cunrentData = this.getCurrentDate('/')
      this.SeatNumberFormDataFlage = true
    },
    handleImport(row) {
      this.importInfo.show = true
      this.importInfo.fileName = row.skuNo
      this.importInfo.query = {
        skuNo: row.skuNo,
        skuId: row.skuId,
        id: row.id,
      }
    },
    cancelExpirationTime() {
      this.ExpirationTime = false
      this.QuantityReceived.ExpirationTimevalue = ''
      this.QuantityReceived.serializableIdList = []
    },
    setExpirationTime() {
      setIsExpiredTime({
        setAll: this.QuantityReceived.setAll,
        skuId: this.QuantityReceived.skuId,
        purchaseId: this.QuantityReceived.id,
        isExpiredTime: this.QuantityReceived.ExpirationTimevalue,
        serializableIdList: this.QuantityReceived.serializableIdList,
      }).then((res) => {
        this.ExpirationTime = false
        this.QuantityReceived.ExpirationTimevalue = ''
        this.QuantityReceived.serializableIdList = []
        this.$message.success(res.msg)

        if (this.isPage == 1) {
          this.relaodvList()
        } else if (this.isPage == 2) {
          this.getPageDiliverList()
        }
      })
    },
    /**设置过期时间 */
    subExpirationTime(type, data) {
      this.ExpirationTime = !this.ExpirationTime
      this.QuantityReceived.setAll = type
      if (data != null) {
        this.QuantityReceived.serializableIdList = [data.id]
        this.$set(this.QuantityReceived, 'ExpirationTimevalue', data.isExpiredTime != '-' ? data.expiredTime : '')
      }
      if (this.QuantityReceived.ExpirationTimevalue == '-') {
        this.QuantityReceived.ExpirationTimevalue = ''
      }
      // console.log(`QuantityReceived ==>`, JSON.parse(JSON.stringify(this.QuantityReceived)))
    },
    handleTransportScrap() {
      this.transportScrap.show = true
    },
    handleWarehouseScrap() {
      this.warehouseScrap.show = true
    },
    /**查询分页分配列表 */
    getPageDiliverList() {
      getSkuSerializableListBySkuIdPurchaseIdByPage(this.diliverInfo.queryParams).then((res) => {
        const { code, rows, total } = res
        if (code === 200) {
          this.diliverInfo.pageData = rows
          this.diliverInfo.pageData.forEach((item) => {
            item.expiredTime = item.expiredTime?.split(' ')[0]
          })
          this.diliverInfo.pageTotal = total
        }
      })
    },
    resetSelectData(e) {
      // console.log(` ==>`, JSON.parse(JSON.stringify(e)));
      this.diliverInfo.tableCheck = []
      if (e == 2) {
        this.getPageDiliverList()
        this.diliverInfo.data.forEach((i) => (i.check = false))
      } else {
        this.relaodvList()
      }
    },
    /**重查虚拟列表 */
    relaodvList() {
      getSkuSerializableListBySkuIdPurchaseId({
        purchaseId: this.QuantityReceived.id,
        skuId: this.QuantityReceived.skuId,
      }).then((res) => {
        this.handleVListData(res.data)
      })
    },
    getRowKey(row) {
      return row.id // 使用唯一标识符作为行的 key
    },
    // 获取供应商下拉数据
    getDistributorList() {
      distributorList({ type: 2 }).then((response) => {
        this.selectUserTypeList = response.rows
      })
    },
    /**当前年月日 */
    getCurrentDate(format) {
      const currentDate = new Date() // 创建一个Date对象来表示当前日期和时间
      const year = currentDate.getFullYear() // 获取当前年份
      const month = currentDate.getMonth() + 1 // 获取当前月份（注意：月份从0开始，所以要加1）
      const day = currentDate.getDate() // 获取当前日期（天）

      // 如果你需要获取其他时间信息，比如小时、分钟、秒，也可以继续使用Date对象的方法

      // 返回一个包含年、月、日的字符串
      return `${year}${format}${month}${format}${day}`
    },
    startLoading() {
      this.loadingInstance = Loading.service({
        text: 'Loading...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
    },
    endLoading() {
      this.loadingInstance?.close()
    },
    printQrCode() {
      this.startLoading()
      let cunrentData = this.getCurrentDate('/')
      let userId = sessionStorage.getItem('userId')
      const data = JSON.parse(JSON.stringify(this.diliverInfo.tableCheck))
      this.diliverInfo.qrData = data.map((i) => {
        return {
          ...i,
          id: i.id,
          skuNo: this.QuantityReceived.skuNo,
          left: cunrentData,
          // right: "ID:" + userId,
          right: this.isPage == '1' ? 'No:' + i.indexNo : 'No:' + i.serial,
          top: this.QuantityReceived.spNo,
        }
      })
      console.log(` ==>`, JSON.parse(JSON.stringify(this.diliverInfo.qrData)))
      this.endLoading()
      setTimeout(() => {
        this.diliverInfo.show = true
      }, 500)
    },
    // 删除序序列号
    deleteDistr(row) {
      this.$confirm(this.$t(`确定删除${row.id}?`), this.$t('提示'), {
        type: 'warning',
      }).then(() => {
        deletePurchaseSkuSerializable({
          purchaseSkuSerializableId: row.id,
        }).then((res) => {
          const { code, data, msg } = res
          if (code === 200) {
            this.$message({ type: 'success', message: msg })

            this.relaodSkuList()
          }
        })
      })
    },
    relaodSkuList() {
      getSkuSerializableListBySkuIdPurchaseId({
        purchaseId: this.QuantityReceived.id,
        skuId: this.QuantityReceived.skuId,
      }).then((res) => {
        this.handleVListData(res.data)
      })

      this.getList()
    },
    // 继续分配
    distributionSerialNumContinue() {
      distributionSerialNumContinue({
        purchaseId: this.QuantityReceived.id,
      }).then((res) => {
        this.$message({ type: 'success', message: res.msg })

        this.relaodSkuList()
      })
    },
    AllSubmit() {
      purchaseSkuSerializableBatch({
        purchaseId: this.BatchScanCodeShelvesForm.data.id,
      }).then((res) => {
        this.$message.success(this.$t('操作成功'))
        this.getList()
      })
    },
    clearBatchScanCodeShelves(type) {
      console.log(type)
      this.scanCodeType = '1'
      this.ShelvesType = 1
      this.BatchScanCodeShelvesList = []
      this.LookBatchScanCodeShelvesList = []
      this.BatchScanCodeShelves = !this.BatchScanCodeShelves
      if (type !== 'cancel') {
        this.getList()
      }
    },
    changeData() {
      var utterance = new SpeechSynthesisUtterance()
      utterance.rate = 2
      this.BatchScanCodeShelvesList.unshift({
        series: this.scanCodeForm.scan,
        status: '0',
      })
      purchaseSkuSerializableScanCode({
        purchaseSkuSerializableId: this.scanCodeForm.scan,
        purchaseId: this.BatchScanCodeShelvesForm.data.id,
      })
        .then((res) => {
          utterance.text = '成功'
          window.speechSynthesis.speak(utterance)
          let arr = []
          this.BatchScanCodeShelvesList.forEach((item) => {
            if (item.series == res.data.data.dictCode) {
              arr.push(item)
            }
          })
          arr[0].status = res.data.data.dictValue

          this.scanCodeForm.scan = ''
        })
        .catch((error) => {
          this.$set(this.BatchScanCodeShelvesList[0], 'status', '4')
          this.scanCodeForm.scan = ''
          utterance.text = error
          window.speechSynthesis.speak(utterance)
        })
    },
    codeScanner(type) {
      this.scanCodeType = type
      if (type == 2) {
        getSkuSerializableListBySkuIdPurchaseId({
          purchaseId: this.BatchScanCodeShelvesForm.data.id,
          skuId: this.BatchScanCodeShelvesForm.data.skuId,
        }).then((res) => {
          this.LookBatchScanCodeShelvesList = res.data
        })
      }
    },
    // 上架弹框
    isShowBatchScanCodeShelves(data) {
      this.BatchScanCodeShelves = !this.BatchScanCodeShelves
      this.BatchScanCodeShelvesForm.data = data
    },
    handlePriceUnit(id) {
      // <!-- 付款总价单位 1-RMB 2-JPY 3-USD -->
      if (id == 1) return 'RMB'
      if (id == 2) return 'JPY'
      if (id == 3) return 'USD'
    },
    setDetailInfoNum() {
      // 单价
      this.detailInfo.form.skuUnitPrice = (+this.detailInfo.form.skuTotalValue / +this.detailInfo.form.num).toFixed(4)
    },
    setDetailInfo() {
      const exchangeRate = this.detailInfo.form.exchangeRate
      // 总货值
      this.detailInfo.form.skuTotalValue = (+this.detailInfo.form.payPrice * +exchangeRate).toFixed(4)

      this.detailInfo.form.skuUnitPrice = (this.detailInfo.form.skuTotalValue / this.detailInfo.form.num).toFixed(4)
    },
    handleSave() {
      const data = JSON.parse(JSON.stringify(this.detailInfo.form))
      this.$refs['saveForm'].validate((valid) => {
        if (valid) {
          console.log(`data ==>`, data)
          updatePurchase(data).then((res) => {
            const { code, data, msg } = res
            if (code === 200) {
              this.$message({ type: 'success', message: msg })

              this.detailInfo.show = false
              this.getList()
            }
          })
        }
      })

      // updatePurchase
    },
    /**查询发货方式 */
    get_deliver_goods_cn_list() {
      useDict('deliver_goods_cn').then(({ deliver_goods_cn }) => {
        this.deliver_goods_cn_list = deliver_goods_cn
      })
    },
    /**采购类型 */
    async getTypeList() {
      await useDict('purchase_type').then(({ purchase_type }) => {
        this.purchase_type_list = purchase_type
      })
    },
    handleDeliveGood(value) {
      /*const name = this.deliver_goods_cn_list.filter((i) => (i.dictValue = value));
      if (name && name.length > 0) {
        return name[0].dictLabel
      }
      return ''*/
      // 20231221 以上代码赋值错误
      const foundItem = this.deliver_goods_cn_list.find((item) => item.dictValue === value)
      return foundItem ? foundItem.dictLabel : ''
    },
    relaod() {
      this.getList()
    },
    handleEdits(row) {
      this.$refs.Skucontmoduler.setSkuInfo(row)
      this.$refs.Skucontmoduler.checkNumber('packingInformation')
    },
    handleDelete(row) {
      this.$confirm(this.$t('确认删除?'), this.$t('提示'), {
        type: 'warning',
      })
        .then(() => {
          deletePurchase(row.id).then((res) => {
            if (res.code == 200) {
              this.$message({ type: 'success', message: res.msg })
              this.getList()
            }
          })
        })
        .catch((e) => e)
    },
    /**分配 */
    handleDiliver(id) {
      distributionSerialNum(id).then((res) => {
        const { code, data, msg } = res
        if (code === 200) {
          this.$message({ type: 'success', message: msg })

          this.getList()
        }
      })
    },
    // 关闭已分配弹框
    allocationFlageClose() {
      this.isPage = '1'
      this.diliverInfo = {
        qrData: [],
        tableCheck: [],
        show: false,
        data: [],
        /**分页数据 */
        pageData: [],
        pageTotal: 0,

        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 20,
          purchaseId: '',
          skuId: '',
        },
      }
      this.allocationFlage = !this.allocationFlage
    },
    /**
     * 处理虚拟表格数据
     */
    handleVListData(data) {
      this.diliverInfo.data = data.map((item, index) => {
        const { isOutWarehouse, isOnShelf, isBox } = item
        /************************出库情况***********************/
        let isOutWarehouseText, isOutWarehouseStyle
        if (isOutWarehouse == 0) {
          isOutWarehouseText = '未出库'
          isOutWarehouseStyle = { color: 'red' }
        } else if (isOutWarehouse == 1) {
          isOutWarehouseText = '已出库'
          isOutWarehouseStyle = { color: '#13ce66' }
        }
        /************************出库情况 end***********************/

        /************************上架情况***********************/
        let isOnShelfText, isOnShelfStyle
        if (isOnShelf == 0) {
          isOnShelfText = '未上架'
          isOnShelfStyle = { color: 'red' }
        } else if (isOnShelf == 1) {
          isOnShelfText = '已上架'
          isOnShelfStyle = { color: '#13ce66' }
        }
        /************************上架情况 end ***********************/

        /************************装箱情况***********************/
        let isBoxText, isBoxStyle
        // 是否装箱 0-否 1-是
        if (isBox == 0) {
          isBoxText = '否'
          isBoxStyle = { color: 'red' }
        } else if (isBox == 1) {
          isBoxText = '是'
          isBoxStyle = { color: '#13ce66' }
        }
        // /**过期时间处理 */
        // if (item.isExpired == 0) {
        //   item.expiredTime = '-'
        // } else {
        //   item.expiredTime = item.expiredTime?.split(' ')[0]
        // }
        /************************装箱情况 end ***********************/
        return {
          ...item,
          index,
          expiredTime: item.expiredTime?.split(' ')[0] || '-',
          indexNo: index + 1,
          idText: item.id,
          isOutWarehouseText,
          isOutWarehouseStyle,
          isOnShelfText,
          isOnShelfStyle,
          isBoxText,
          isBoxStyle,
          check: false,
        }
      })
    },
    /**分配详情 */
    handleDiliverDetail(row) {
      const { id, skuId } = row
      /********************分配详情********************/
      this.diliverInfo.queryParams.purchaseId = id
      this.diliverInfo.queryParams.skuId = skuId
      /********************分配详情end********************/
      this.QuantityReceived = row
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
      getSkuSerializableListBySkuIdPurchaseId({ purchaseId: id, skuId }).then((res) => {
        loading.close()
        this.allocationFlage = !this.allocationFlage
        this.handleVListData(res.data)
      })
    },
    /** 装箱数量*/
    handleEncasementNum(row) {
      this.encasementNum.formData = { ...row }
      this.encasementNum.show = true
    },

    confirmEncasementNum() {
      this.$refs.encasementNumForm.validate((valid) => {
        if (valid) {
          batchEncasement(this.encasementNumInfo.form).then((res) => {
            const { code, data, msg } = res
            if (code === 200) {
              this.$message({ type: 'success', message: msg })

              this.getList()
              this.encasementNumInfo.show = false
            }
          })
        }
      })
    },
    /**确认收货 */
    confirmReceiveGoods() {
      const { num, receiveGoodsNum } = this.receiveGoodsInfo.form
      if (receiveGoodsNum > num) {
        this.$message.error('收货数量不能大于采购数量')
        return
      }
      this.$refs.receiveGoodsForm.validate((valid) => {
        if (valid) {
          confirmReceiveGoods(this.receiveGoodsInfo.form).then((res) => {
            const { code, data, msg } = res
            if (code === 200) {
              this.$message({ type: 'success', message: msg })

              this.getList()
              this.receiveGoodsInfo.show = false
            }
          })
        }
      })
    },
    handleReceiveGoods(row) {
      console.log(`row ==>`, JSON.parse(JSON.stringify(row)))
      this.receiveGoodsInfo.form = JSON.parse(JSON.stringify(row))
      // this.receiveGoodsInfo.form.payPriceUnit = 1
      this.receiveGoodsInfo.show = true
    },
    async handleDetail(row) {
      this.getTypeList()
      await getConversionRateList().then((res) => {
        this.exchangeRateList = res.data
      })
      await getPurchaseInfo(row.id).then((res) => {
        this.detailInfo.show = true
        this.detailInfo.form = JSON.parse(JSON.stringify(res.data))

        const payPriceUnit = this.detailInfo.form.payPriceUnit

        let exchangeRate

        // 付款总价单位 1-RMB 2-JPY 3-USD
        if (payPriceUnit == 1) {
          const rate = this.exchangeRateList?.filter((i) => i.baseCode == 'CNY')
          exchangeRate = rate[0].conversionRate
        }
        if (payPriceUnit == 2) {
          exchangeRate = 1
        }
        if (payPriceUnit == 3) {
          const rate = this.exchangeRateList?.filter((i) => i.baseCode == 'USD')
          exchangeRate = rate[0].conversionRate
        }
        this.detailInfo.form.exchangeRate = exchangeRate
      })
    },
    getSkuList(skuNo) {
      getSkuList(skuNo).then((res) => {
        this.skuList = res.data
      })
    },
    /**获取供应厂商列表  （厂家） */
    getManufacturers() {
      listManufacturers().then((res) => (this.manufacturersList = res.rows))
    },
    handleAdd() {
      this.showName = 'add'
      this.showDialog = true
      this.form.skuId = ''
      this.getSkuList()
    },
    handleEdit(row) {
      this.showName = 'edit'
      const _row = JSON.parse(JSON.stringify(row))
      const time = _row.operateTime.split('-')
      _row.operateStartTime = time[0]
      _row.operateEndTime = time[1]
      this.form = _row
      this.showDialog = true
    },

    /** 查询菜单列表 */
    getList() {
      this.loading = true

      if (this.queryParams.purchaseTime && this.queryParams.purchaseTime.length > 0) {
        this.queryParams.purchaseStartTime = this.queryParams.purchaseTime[0]
        this.queryParams.purchaseEndTime = this.queryParams.purchaseTime[1]
      }
      getPurchaseList(this.queryParams)
        .then((res) => {
          this.tableData = res.rows
          this.pageTotal = res.total
          this.loading = false
        })
        .finally(() => (this.loading = false))
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.value1 = null
      Object.keys(this.queryParams).forEach((key) => {
        this.queryParams[key] = null
      })
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10

      this.getList()
    },
  },
}
</script>
<style lang="scss" scoped>
.PagingList {
  ::v-deep .el-table--medium .el-table__cell {
    padding: 0 !important;
    line-height: 25px;
    height: 25px !important;
  }
  ::v-deep .el-button--medium {
    padding: 0 0px;
  }
}
.goods {
  &-img {
    &-box {
      position: relative;
    }

    &-mini {
      height: 50px;
      border-radius: 3px;

      &:hover {
        & + .goods-img-big {
          display: block;
        }
      }
    }

    &-big {
      // display: none;
      position: absolute;
      z-index: 100;
      top: -180px;
      left: 0;
      transform: translate(0, 70px);
      width: 200px;
      height: 200px;
      border-radius: 3px;
    }
  }
}
.bigImg {
  border-radius: 3px;
  z-index: 10;
  position: fixed;
  width: 200px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
#printArea {
  display: flex;
  flex-direction: column;
  align-items: center;
  // width: 50px;
  margin: 0 auto;
  // max-height: 500px;
  // overflow: auto;

  .print-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 55px;
    margin: 0 4px 4px 4px;
    font-size: 12px;
    // margin-bottom: 7mm !important;
  }
}

.beatchAllFather {
  height: 400px;
}

.beatchAll {
  background-color: #e1eafc;
  border-radius: 5px;
  padding: 20px;
}

.beatchAllFooter {
  position: absolute;
  right: 40px;
  bottom: 40px;
}

.batchTitle {
  text-align: center;
}

.checkType {
  text-align: center;
  margin-bottom: 20px;
}

::v-deep .myDialog {
  & > .el-dialog {
    & > .el-dialog__body {
      padding: 0 20px 30px 20px !important;
    }
  }
}

.checkTypesContent {
  display: flex;

  & > :first-child {
    margin-right: 10px;
  }
}

.activecheckTypes {
  background-color: blue !important;
}

.checkTypes {
  padding: 0 4px;
  color: white;
  cursor: pointer;
  line-height: 30px;
  border-radius: 5px 5px 0 0;
  background-color: rgb(101, 160, 209);
  height: 30px;
}

.contentList {
  border: solid 1px black;
  height: 400px;
  overflow-y: scroll;

  .fatherContent {
    display: flex;
    width: 100%;
    justify-content: space-around;

    .seriesNum {
      border: solid 1px black;
      width: 50%;
      text-align: center;
      padding: 6px;
    }

    .ShelfStatus {
      border: solid 1px black;
      width: 50%;
      text-align: center;
      padding: 6px;
    }
  }
}

@page {
  /* margin: 距离打印纸下边 右边 2mm 真实打印右边; */
  margin: 2mm 0px 4px 2px;
  width: 30mm;
  height: 20mm;
}
.VList {
  padding-bottom: 20px;
}
</style>
